package com.zs.dao;

import com.zs.entity.Admin;
import com.zs.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class AdminDao {

    Connection connection = DBUtil.getConnection();
    PreparedStatement pstmt = null;
    ResultSet rs = null;

    public Admin adminLogin(String aname, String apwd) {
        Admin admin = null;
        String sql = "select * from t_admin where aname = ? and apwd = ?";
        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, aname);
            pstmt.setString(2, apwd);
            rs = pstmt.executeQuery();

            if (rs.next()) {
                admin = new Admin();
                admin.setId(rs.getInt("id"));
                admin.setAname(rs.getString("aname"));
                admin.setApwd(rs.getString("apwd"));
                admin.setPhone(rs.getString("phone"));
                admin.setEmail(rs.getString("email"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return admin;
    }

    public void addAdmin(Admin admin) {
        String sql = "insert into t_admin(aname,apwd,phone,email) values (?,?,?,?)";

        try {
            pstmt = connection.prepareStatement(sql);
            pstmt.setString(1, admin.getAname());
            pstmt.setString(2, admin.getApwd());
            pstmt.setString(3, admin.getPhone());
            pstmt.setString(4, admin.getEmail());
            pstmt.executeUpdate();


        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    public List<Admin> getAllAdmin() {
        List<Admin> list = new ArrayList<>();
        try {
            String sql = "select * from t_admin";
            pstmt = connection.prepareStatement(sql);
            rs = pstmt.executeQuery();

            while (rs.next()) {
                Admin admin = new Admin();
                admin.setId(rs.getInt("id"));
                admin.setAname(rs.getString("aname"));
                admin.setApwd(rs.getString("apwd"));
                admin.setPhone(rs.getString("phone"));
                admin.setEmail(rs.getString("email"));

                list.add(admin);
            }


        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

}
